package com.linnas.filter;

import com.alibaba.fastjson.JSON;
import com.linnas.common.BaseContext;
import com.linnas.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("拦截到请求: {}", request.getRequestURI());

        //1. 获取本次请求uri
        String requestURI = request.getRequestURI();
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        //2. 判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3. 不需要处理直接放行
        if (check) {
            log.info("已放行");
            chain.doFilter(request, response);
            return;
        }

        //4.1 若用户已登录直接放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            log.info("员工账号密码登录: {}", empId);
            BaseContext.setCurrentId(empId);
            chain.doFilter(request, response);
            return;
        }

        //4.1 手机号登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            log.info("用户手机号登录: {}", userId);
            BaseContext.setCurrentId(userId);
            chain.doFilter(request, response);
            return;
        }

        //5. 未登录处理，通过输出流向客户端页面响应数据
        log.info("不能放行");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    @Override
    public void destroy() {

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
